<?php
//+----------------------------------------------------
//| 工具类: SMS短信验证码工具类
//| Author: web_dxj@163.com
//+----------------------------------------------------

namespace Api\Libs;

class SmsUtil {

	/**
	 * 构造函数
	 */
	public function __construct() {}


    /**
     * 生成短信验证码
     * @return string 返回生成的6位短信验证码
     */
    private function createSmsCode() {

        // 移动电信黑名单
        $forbidden_num = "1989:10086:12590:1259:10010:10001:10000:";
        do {
            $code = substr(microtime(), 2, 6);
        } while (preg_match($code.':', $forbidden_num));

        return $code;
    }

	/**
	 * 发送验证码
	 * @param  string $to   短信接收方电话号码
	 * @return array  		返回验证码的发送结果状态码
	 */
	public function sendCode($to) {

        // 获取云之讯配置
        $options['accountsid'] = C ('YUN_ACCOUNTSID');
        $options['token'] = C ('YUN_TOKEN');
        $Ucpass = new \Api\Libs\Ucpaas($options);

		$appId = C ('YUN_APPID');
		$templateId = C ('YUN_TEMPLATEID');

        $code = $this->createSmsCode();

        // 组合短信参数,根据短信预留位置填充
		$param = $code . ',' . C ('YUN_CODEUSETIME');
        // 调用发送短信接口
		$resp = $Ucpass->templateSMS($appId,$to,$templateId,$param);
		//$res = '{"resp":{"respCode":"000000","templateSMS":{"createDate":"20150327151332","smsId":"dda5861f8266eb626928f3ed39410ffd"}}}';
		
		return array('smsCode'=>$code,'respCode'=>$this->handlerRespJson($resp));
	}


	/**
	 * 处理云之讯返回的json语句
	 * @param  string $json json语句
	 * @return string       resCope
	 */
	private function handlerRespJson($json) {
		$obj_json = json_decode($json,true);
		return $obj_json['resp']['respCode'];
	}


}